package com.iwords.android;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.methods.HttpPost;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.widget.Toast;

public class WordLibsManager {
	IWordsApp iWordsApp;
	Activity activity;
	public WordLibsManager(IWordsApp iWordsApp, Activity activity){
		this.iWordsApp = iWordsApp;
		this.activity = activity;
	}
	
    static class WordLib{
    	public WordLib(String libName, Long libId, Long pId, Boolean selected, Integer syslibLevel, Boolean isLeaf){
    		this.libName = libName;
    		this.libId = libId;
    		this.pId = pId;
    		this.selected = Boolean.FALSE;
    		this.syslibLevel = syslibLevel;
    		this.isLeaf = isLeaf;
    	}
    	String libName;//课本名称
    	Long libId;//课本ID
    	Long pId;//父ID
    	Boolean selected;//课本选中状态
    	Integer syslibLevel;//课本的分类层级
    	Boolean isLeaf;//课本是否叶子节点
    	public String toString(){
    		return libName+" libId:"+libId+" libLevel:"+syslibLevel+" selected:"+selected+" isLeaf: "+isLeaf;
    	}
    }
    static final List<WordLib> WordLibs = new ArrayList<WordLib>();
    static final List<WordLib> CurrentLibs = new ArrayList<WordLib>();
    private void loadWordLibs(){
    	//System.out.println("ShowWordLib.loadWordLibss() WordLibs.size()="+WordLibs.size());
		String href = iWordsApp.getResources().getString(R.string.book_list);
		HttpPost request = new HttpPost(href);
		//System.out.println("ShowWordLib.loadWordLibs()!");
		try {

			JSONObject jSONObject = ServerAccessor.access(iWordsApp, request);
			boolean success = jSONObject.getBoolean("isSuccess");
			//System.out.println("IWords.loginHandler() success = " + success);
			if(success){
				JSONArray jsonArray = JSONUtils.getArray(jSONObject.getJSONObject("defaultValue"));
				for(int i=0; i<jsonArray.length();i++){
					JSONObject jsonObject = jsonArray.getJSONObject(i);
					WordLib wordLib = new WordLib(
							CodeUtils.decode(jsonObject.getString("libname")),
							jsonObject.getLong("libid"), 
							jsonObject.getLong("pid"), 
							Boolean.FALSE, 
							jsonObject.getInt("sysliblevel"), 
							(jsonObject.getInt("sysliblevel")==4));
							//jsonObject.getBoolean("isLeaf"));
					WordLibs.add(wordLib);
				}
			}else{
				String message = CodeUtils.decode(jSONObject.getString("message"));
				this.displayMessage(message);
			}
		} catch(NeedPayException ne){
			Intent intent = new Intent(iWordsApp, com.iwords.android.AlipayActivity.class);
			iWordsApp.startActivity(intent);
		} catch (Exception e) {
			this.displayMessage(e.getMessage());
		}    	
    }
    /**根据当前词库的信息，设定当前词库选择列表的数据。
     * 三种场景：
     * 1. 用户第一次选择课本（比如刚下载客户端），显示pid为1的课本分类（此时也肯定没有用户词库）
     * 2. 用户在选择课本的流程中，选择了非叶子节点的课本树节点，需要装配选择节点的子节点作为List的内容。
     *    intent中包含属性selectedLibID
     * 3. 如果用户在背单词界面，切换到课本选择界面，则显示当前词库同一级别的节点作为List的内容。
     *    intent中包含参数，currentWordLibId
     */
    void packChildrenAsList(Long pid){
    	//System.out.println("WordLibsManager.packChildrenAsList() pid="+pid);
    	CurrentLibs.clear();
		if(WordLibs.size()<1){
			this.loadWordLibs();
		}
		
		for(WordLib lib : WordLibs){
			//System.out.println("currentWordLibId = "+pid+" lib.pId="+lib.pId);
			if(pid.equals(lib.pId)){
				CurrentLibs.add(lib);
			}
		}
    }
    Long packSistersAsList(Long libId){
    	//System.out.println("WordLibsManager.packSistersAsList() libId="+libId);
		if(WordLibs.size()<1){
			this.loadWordLibs();
		}
		
		Long pid = 1L;
		for(WordLib lib : WordLibs){
			//System.out.println("currentWordLibId = "+libId+" lib.id="+lib.libId+" lib.pId="+lib.pId);
			if(libId.equals(lib.libId)){
				pid = lib.pId;
			}
		}
		this.packChildrenAsList(pid);
		return pid;
    }

    WordLibsManager.WordLib getWordLib(Long libId){
    	for(WordLib lib : WordLibs){
    		if(libId.equals(lib.libId)) return lib;
    	}
    	return null;
    }
    
    Long getParent(Long libId){
    	Long pid = null;
		for(WordLib lib : WordLibs){
			//System.out.println("currentWordLibId = "+libId+" lib.id="+lib.libId+" lib.pId="+lib.pId);
			if(libId.equals(lib.libId)) pid = lib.pId;
		}
		return pid;
    }
	private void displayMessage(String message){
		Toast t1 = Toast.makeText(iWordsApp, message, Toast.LENGTH_LONG);
		t1.show();
	}
}
